package ro.myApp.articles.client;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;

import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.international.StatusMessage.Severity;
import org.jboss.seam.security.Identity;
import org.richfaces.event.UploadEvent;
import org.richfaces.model.UploadItem;

import ro.myApp.articles.dto.PublicationCreateNewMessage;
import ro.myApp.articles.dto.PublicationFindAllMessage;
import ro.myApp.articles.dto.PublicationSaveNewMessage;
import ro.myApp.articles.entities.Publication;
import ro.myApp.client.BaseView;

public class DocumentList<F extends Publication> extends BaseView implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = -8229153181038398980L;

	private Class<F> clazz;
	
	private F document;
	
	private List<F> documents;
	
	public DocumentList(Class<F> clazz) {
		this.clazz=clazz;
	}
	
	public F getDocument() {
		if (null==document){
			Object res = sendMessage(new PublicationCreateNewMessage(clazz));
			document=(F) res;
		}
		return document;
	}
	
	public List<F> getDocuments() {
		if (null==documents){
			PublicationFindAllMessage m = new PublicationFindAllMessage();
			m.setForUser(Identity.instance().getCredentials().getUsername());
			documents = sendMessage(m);
		}
		return documents;
	}
	
	@SuppressWarnings("unchecked")
	public void save (){
		Object result = sendMessage(new PublicationSaveNewMessage((Publication)document));
		documents.add(0, (F) result);
	}
	
	public void cancel(){
		document = null;
	}
	
	/**
	 * listener for upload richfaces component
	 */
	public void upload(UploadEvent event){
		UploadItem item = event.getUploadItem();
		//create attachment 
		document.setCode(item.getFileName());
		try {
			File file=item.getFile();
			FileInputStream fin = new FileInputStream(file);
			byte[] buf = new byte[(int)file.length()];
			// Read in the bytes
			int offset = 0;
			int numRead = 0;
			while (offset < buf.length && (numRead = fin.read(buf, offset, buf.length - offset)) >= 0) {
				offset += numRead;
			}
			// Ensure all the bytes have been read in
			if (offset < buf.length) {
				throw new IOException("Could not completely read file " + file.getName());
			}
			// Close the input stream and return bytes
			fin.close();
			
			document.setDocument(buf);
		} catch (Exception e) {
			FacesMessages.instance().addFromResourceBundle(Severity.ERROR,"FileTooBig");
		}
	}
}
